package com.ruoyi.web.controller.estate;

import java.util.List;
import java.util.ArrayList;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.estate.Repair;
import com.ruoyi.system.service.estate.IRepairService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.SecurityUtils;

/**
 * 维修信息Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/estate/repair")
public class RepairController extends BaseController
{
    @Autowired
    private IRepairService repairService;

    /**
     * 查询维修信息列表
     */
    @PreAuthorize("@ss.hasPermi('estate:repair:list')")
    @GetMapping("/list")
    public TableDataInfo list(Repair repair)
    {
        startPage();
        List<Repair> list = repairService.selectRepairList(repair);
        return getDataTable(list);
    }

    /**
     * 导出维修信息列表
     */
    @PreAuthorize("@ss.hasPermi('estate:repair:export')")
    @Log(title = "维修信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Repair repair)
    {
        List<Repair> list = repairService.selectRepairList(repair);
        ExcelUtil<Repair> util = new ExcelUtil<Repair>(Repair.class);
        return util.exportExcel(list, "维修信息数据");
    }

    /**
     * 获取维修信息详细信息（管理员访问）
     */
    @PreAuthorize("@ss.hasPermi('estate:repair:query')")
    @GetMapping(value = "/admin/{repairId}")
    public AjaxResult getAdminInfo(@PathVariable("repairId") Long repairId)
    {
        return AjaxResult.success(repairService.selectRepairById(repairId));
    }

    /**
     * 获取维修信息详细信息（用户访问）
     */
    @GetMapping(value = "/{repairId}")
    public AjaxResult getInfo(@PathVariable("repairId") Long repairId)
    {
        // 获取当前用户ID
        Long userId = SecurityUtils.getUserId();
        
        // 获取报修信息
        Repair repair = repairService.selectRepairById(repairId);
        
        // 验证是否是当前用户的报修
        if (repair != null) {
            // 根据用户ID查询关联的住户ID
            List<Repair> userRepairs = repairService.selectRepairListByUserId(userId);
            boolean isUserRepair = userRepairs.stream()
                .anyMatch(r -> r.getRepairId().equals(repairId));
            
            if (isUserRepair) {
                return AjaxResult.success(repair);
            } else {
                return AjaxResult.error("您无权查看此报修信息");
            }
        }
        
        return AjaxResult.error("报修信息不存在");
    }

    /**
     * 新增维修信息
     */
    @PreAuthorize("@ss.hasPermi('estate:repair:add')")
    @Log(title = "维修信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Repair repair)
    {
        return toAjax(repairService.insertRepair(repair));
    }

    /**
     * 修改维修信息
     */
    @PreAuthorize("@ss.hasPermi('estate:repair:edit')")
    @Log(title = "维修信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Repair repair)
    {
        return toAjax(repairService.updateRepair(repair));
    }

    /**
     * 删除维修信息
     */
    @PreAuthorize("@ss.hasPermi('estate:repair:remove')")
    @Log(title = "维修信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{repairIds}")
    public AjaxResult remove(@PathVariable Long[] repairIds)
    {
        return toAjax(repairService.deleteRepairByIds(repairIds));
    }
    
    /**
     * 提交报修
     */
    @Anonymous
    @Log(title = "提交报修", businessType = BusinessType.INSERT)
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody Repair repair)
    {
        return toAjax(repairService.submitRepair(repair));
    }
    
    /**
     * 获取我的报修记录
     */
    @Anonymous
    @GetMapping("/my")
    public AjaxResult myRepairs()
    {
        try {
            Long userId = SecurityUtils.getUserId();
            List<Repair> list = repairService.selectRepairListByUserId(userId);
            return AjaxResult.success(list);
        } catch (Exception e) {
            // 用户未登录或会话过期，返回空列表
            return AjaxResult.success(new ArrayList<>());
        }
    }
    
    /**
     * 取消报修
     */
    @Log(title = "取消报修", businessType = BusinessType.UPDATE)
    @PutMapping("/cancel/{repairId}")
    public AjaxResult cancel(@PathVariable("repairId") Long repairId)
    {
        return toAjax(repairService.cancelRepair(repairId));
    }
    
    /**
     * 评价报修
     */
    @Log(title = "评价报修", businessType = BusinessType.UPDATE)
    @PutMapping("/evaluate")
    public AjaxResult evaluate(@RequestBody Repair repair)
    {
        return toAjax(repairService.evaluateRepair(repair));
    }
} 